package com.zzyl.common.core.controller;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.core.page.PageDomain;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.core.page.TableSupport;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.PageUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.sql.SqlUtil;

/**
 * web层通用数据处理
 *
 * @author ruoyi
 */
@Api(tags = "基础控制器", description = "提供基础的控制器功能，包括分页、数据绑定、结果返回等")
public class BaseController
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    @ApiOperation(value = "初始化数据绑定", notes = "注册自定义编辑器，将字符串日期转换为Date类型")
    @ApiResponses({
        @ApiResponse(code = 200, message = "处理成功")
    })
    public void initBinder(@ApiParam(name = "binder", value = "Web数据绑定器", required = true) WebDataBinder binder)
    {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    @ApiOperation(value = "设置请求分页数据", notes = "根据请求参数初始化分页信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "处理成功")
    })
    protected void startPage()
    {
        PageUtils.startPage();
    }

    /**
     * 设置请求排序数据
     */
    @ApiOperation(value = "设置请求排序数据", notes = "根据请求参数初始化排序信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "处理成功")
    })
    protected void startOrderBy()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }

    /**
     * 清理分页的线程变量
     */
    @ApiOperation(value = "清理分页的线程变量", notes = "清除当前线程中的分页参数")
    @ApiResponses({
        @ApiResponse(code = 200, message = "处理成功")
    })
    protected void clearPage()
    {
        PageUtils.clearPage();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @ApiOperation(value = "响应请求分页数据", notes = "封装分页结果数据")
    @ApiResponses({
        @ApiResponse(code = 200, message = "处理成功")
    })
    protected TableDataInfo getDataTable(@ApiParam(name = "list", value = "数据列表", required = true) List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 返回成功
     */
    @ApiOperation(value = "返回成功结果", notes = "返回操作成功的统一响应结果")
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功")
    })
    public AjaxResult success()
    {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    @ApiOperation(value = "返回失败结果", notes = "返回操作失败的统一响应结果")
    @ApiResponses({
        @ApiResponse(code = 500, message = "操作失败")
    })
    public AjaxResult error()
    {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    @ApiOperation(value = "返回带消息的成功结果", notes = "返回操作成功的统一响应结果，包含自定义消息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功")
    })
    public AjaxResult success(@ApiParam(name = "message", value = "返回消息", required = true) String message)
    {
        return AjaxResult.success(message);
    }

    /**
     * 返回成功消息
     */
    @ApiOperation(value = "返回带数据的成功结果", notes = "返回操作成功的统一响应结果，包含业务数据")
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功")
    })
    public AjaxResult success(@ApiParam(name = "data", value = "返回数据", required = true) Object data)
    {
        return AjaxResult.success(data);
    }

    /**
     * 返回失败消息
     */
    @ApiOperation(value = "返回带消息的失败结果", notes = "返回操作失败的统一响应结果，包含错误消息")
    @ApiResponses({
        @ApiResponse(code = 500, message = "操作失败")
    })
    public AjaxResult error(@ApiParam(name = "message", value = "错误消息", required = true) String message)
    {
        return AjaxResult.error(message);
    }

    /**
     * 返回警告消息
     */
    @ApiOperation(value = "返回警告消息", notes = "返回警告状态的统一响应结果")
    @ApiResponses({
        @ApiResponse(code = 400, message = "警告信息")
    })
    public AjaxResult warn(@ApiParam(name = "message", value = "警告消息", required = true) String message)
    {
        return AjaxResult.warn(message);
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    @ApiOperation(value = "根据影响行数返回操作结果", notes = "根据数据库操作影响行数判断操作是否成功")
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功"),
        @ApiResponse(code = 500, message = "操作失败")
    })
    protected AjaxResult toAjax(@ApiParam(name = "rows", value = "影响行数", required = true) int rows)
    {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    @ApiOperation(value = "根据布尔结果返回操作结果", notes = "根据布尔值判断操作是否成功")
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功"),
        @ApiResponse(code = 500, message = "操作失败")
    })
    protected AjaxResult toAjax(@ApiParam(name = "result", value = "操作结果", required = true) boolean result)
    {
        return result ? success() : error();
    }

    /**
     * 页面跳转
     */
    @ApiOperation(value = "页面重定向", notes = "生成重定向URL")
    @ApiResponses({
        @ApiResponse(code = 302, message = "重定向")
    })
    public String redirect(@ApiParam(name = "url", value = "重定向URL", required = true) String url)
    {
        return StringUtils.format("redirect:{}", url);
    }

    /**
     * 获取用户缓存信息
     */
    @ApiOperation(value = "获取登录用户信息", notes = "获取当前登录用户的信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功")
    })
    public LoginUser getLoginUser()
    {
        return SecurityUtils.getLoginUser();
    }

    /**
     * 获取登录用户id
     */
    @ApiOperation(value = "获取登录用户ID", notes = "获取当前登录用户的唯一标识")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功")
    })
    public Long getUserId()
    {
        return getLoginUser().getUserId();
    }

    /**
     * 获取登录部门id
     */
    @ApiOperation(value = "获取登录用户部门ID", notes = "获取当前登录用户所属部门的唯一标识")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功")
    })
    public Long getDeptId()
    {
        return getLoginUser().getDeptId();
    }

    /**
     * 获取登录用户名
     */
    @ApiOperation(value = "获取登录用户名", notes = "获取当前登录用户的名称")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功")
    })
    public String getUsername()
    {
        return getLoginUser().getUsername();
    }
}
